﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace FeCMS.UrlRoute
{
    /// <summary>
    ///     解析用户请求
    /// </summary>
    public class ExPageRequest
    {
        // 用于匹配Ajax请求的正则表达式，
        // 可以匹配的URL：/AjaxClass/method.cspx?id=2
        // 注意：类名必须Ajax做为前缀
        internal static readonly string AjaxUrlPattern
            = @"/(?<name>(\w[\./\w]*)?(?=Ajax)\w+)[/\.](?<method>\w+)\.[a-zA-Z]+";

        /// <summary>
        ///     解析请求，并把请求分解成请求包
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static ExRequestPack Parse(HttpContext context)
        {
            //1.根据请求的Url跟Route对比，找出相应的规则
            string path = context.Request.Path;

            int len = MapRoute.Instance.IndexLen;
            for (int i = 0; i < len; i++)
            {
                Match match = Regex.Match(path, MapRoute.Instance.GetUrlRule(i));
                if (match.Success)
                {
                    var route = MapRoute.Instance.GetRoutePack(i);
                    ExRequestPack pack = new ExRequestPack() { 
                     Action =route.Action,// match.Groups["action"].Value,
                     Controller =route.Controller,// match.Groups["controller"].Value,
                     ControllerType = route.ControllerType,
                     TemplatePath = route.TemplatePath,
                     DataSoure =route.DataSoure
                    };
                    //2.把MVC请求的参数放到第二个数据层级
                    pack.DataSoure.MoveToNextLevel();
                    for (int n = 0, m = match.Groups.Count; n < m; n++)
                    {
                        match.Groups[]
                        pack.DataSoure.AppendLableData(match.Groups[i].Value);
                    }
                        return pack;
                }
            }
            //没查到就返回404
            //TODO:404
            return null;
        }

    }
}
